const http = require("../../api/camp")
const {
    baseURL
  } = require("../../utils/request")
// pages/shop/shop.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    obj:{
        userId:"",
        campId:"",
        total:"",
        qrcode:'', //二维码
        orderDetails:[]
    },
      qrCodeImage:"",
      flag:false,
      cartLength:0,
      showCart:false,
      amount:0,
      campId:"",
    cartList:[],//购物车数据
    goodsList:[],//商品数据
    appointmentList:{},
    active:0,
    currentTab:0,
    baseURL:baseURL,
    goodsNum:0,//商品数量
    address:""

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    http.getAppointmentByUserId({userId:wx.getStorageSync('userInfo').userId}).then(res=>{
        console.log(res)
        if(res.code==200){
            this.setData({
                appointmentList:res.rows
            })
            console.log("res:",res)
        if (res.rows.length <= 0) {
            return;
          }
          this.setData({
            campId: res.rows[0].camp.campId
          })
          let campId = res.rows[0].camp.campId
          //初始化商品数量
          for(var j=0;j<this.data.appointmentList.length;j++){
            var goodsList=this.data.appointmentList[j].goodsList
            for (let i = 0; i < goodsList.length; i++) {
              goodsList[i].num = 0;
            }
            this.data.appointmentList[j].goodsList=goodsList
            // this.data.appointmentList[j].cartList=[] //初始化购物车
            // this.data.appointmentList[j].sumAmount=0 //总金额
            // this.data.appointmentList[j].setGoodsNum=0 //商品总数量
            this.setData({
                appointmentList:this.data.appointmentList
            })
          }
          console.log("this.data.appointmentList:",this.data.appointmentList)
        }

         
           
    })
    this.getUserLocation();

  },
  switchNav: function (e) {
    var page = this;
    // var id = e.target.id;
    var index = e.target.dataset.index;
    // dataset
    console.log("e=",e)
    if (this.data.currentTab == index) {
      return false;
    } else {
      page.setData({
        currentTab: index
      });
    }
    page.setData({
      active: index
    });
    
    this.setData({
        goodsList:this.data.appointmentList[index].goodsList,
        campId:this.data.appointmentList[index].camp.campId
    })
    console.log("左侧点击之后指定的营地商品：",this.data.goodsList)
    this.setCartList();
    // this.sumAmount();
    // this.setGoodsNum();
  },
// 从本地存储中查询购物车数据
setCartList () {
    var cartList = wx.getStorageSync('cartList-' + this.data.campId)
    if (cartList && cartList.length > 0) {
      this.setData({
        cartList: cartList
      })
    } else {
      this.setData({
        cartList: []
      })
    }
    this.sumAmount();
    this.setGoodsNum();
  },


    // 计算总价
  sumAmount() {
    var cartList = this.data.cartList;
    var amount = 0;
    for (let i = 0; i < cartList.length; i++) {
      const item = cartList[i];
      amount += item.num * item.goodsPrice;
    }
    this.setData({
      amount: amount,
      cartLength: cartList.length
    })
    wx.setStorageSync('cartList-' + this.data.campId, this.data.cartList)
  },

  // 设置商品已经加入购物车的数量
  setGoodsNum() {
    
    var cartList = this.data.cartList;
    var goodsList = this.data.goodsList;
    for (let i = 0; i < cartList.length; i++) {
      const cartItem = cartList[i];
      for (let j = 0; j < goodsList.length; j++) {
        const goodsItem = goodsList[j];
        if (cartItem.goodsId == goodsItem.goodsId) {
          goodsList[j].num = cartItem.num;
          break;
        }
      }
    }
    this.setData({
      goodsList: goodsList
    })
  },

// 当在商品数量变化时
onStepperChange (event) {
    console.log("onStepperChange event", event);
    let index = event.currentTarget.dataset.index;
    var goodsList = this.data.goodsList;
    var cartList = this.data.cartList;

    goodsList[index].num = event.detail;
    // 当商品的选购数量改变时，同步购物车的数量
    // var goodsList = this.data.goodsList;
    var tag = 0;
    for (let j = 0; j < cartList.length; j++) {
      if (goodsList[index].goodsId == cartList[j].goodsId) {
        cartList[j].num = goodsList[index].num;
        tag++;
        break;
      }
    }
    if (tag == 0) {
      cartList.push(goodsList[index])
    }
    
    const uniqueCartList = cartList.filter((item, index, self) => {
      return index === self.findIndex(obj => obj.goodsId === item.goodsId) && item.num > 0;
    });
    this.setData({
      goodsList: goodsList,
      cartList: uniqueCartList,
      cartLength: uniqueCartList.length
    })
    console.log("uniqueCartList", uniqueCartList)

    console.log("cartLength", this.data.cartLength)
    
    this.sumAmount();
  },
// 当在购物车数量变化时
onCartStepperChange (event) {
    console.log("onCartStepperChange event", event);
    let index = event.currentTarget.dataset.index;
    var cartList = this.data.cartList;
    cartList[index].num = event.detail;
    const uniqueCartList = cartList.filter((item, index, self) => {
      return item.num > 0;
    });
    // 当购物车中的数量改变时，同步商品的下标
    var goodsList = this.data.goodsList;
    for (let j = 0; j < goodsList.length; j++) {
      if (cartList[index].goodsId == goodsList[j].goodsId) {
        goodsList[j].num = cartList[index].num;
        break;
      }
    }
    this.setData({
      cartList: uniqueCartList,
      goodsList: goodsList
    })
    var appo=this.data.appointmentList
    appo.goodsList=this.data.goodsList
    this.setData({
        appointmentList:appo
    })
    this.sumAmount();
  },
  getProvinceFromAddress(address) {
    // 地址字符串（示例）
    const addressStr = address;
   
    // 定义一个包含所有省级名称（包括自治区、直辖市等）的数组
    // 注意：这里只列出了部分示例，实际使用时需要补充完整
    const provinces = [
      '北京市', '天津市', '上海市', '重庆市', '河北省', '山西省', '辽宁省', '吉林省', '黑龙江省',
      '江苏省', '浙江省', '安徽省', '福建省', '江西省', '山东省', '河南省', '湖北省', '湖南省',
      '广东省', '海南省', '四川省', '贵州省', '云南省', '陕西省', '甘肃省', '青海省', '台湾省',
      '内蒙古自治区', '广西壮族自治区', '西藏自治区', '宁夏回族自治区', '新疆维吾尔自治区',
      '香港特别行政区', '澳门特别行政区'
    ];
   
    // 将地址字符串按空格分割成数组
    const addressParts = addressStr.split(' ');
   
    // 遍历分割后的数组，查找匹配的省级名称
    for (let i = 0; i < addressParts.length; i++) {
      const part = addressParts[i];
      console.log("part", part)
      for (let j = 0; j < provinces.length; j++) {
        const item = provinces[j];
        
        if (part.includes(item)) {
          return item; // 找到匹配的省级名称，返回
        }
      }
    }
   
    // 如果没有找到匹配的省级名称，返回null或空字符串
    return null; // 或 return '';
  },
  getUserLocation() {
    wx.getLocation({
      // type: 'wgs84',
      type: 'gcj02',
      success: (res) => {
        console.log(res,"返回的数据")
        this.setData({
          latitude: res.latitude,
          longitude: res.longitude,
        //   markers: this.data.markers
        
        });
        wx.chooseLocation({
            latitude: this.data.latitude,
            longitude: this.data.longitude,
            success:(res)=>{
                console.log("chooseLocation 返回的数据",res)
                console.log("getProvinceFromAddress 返回的数据",this.getProvinceFromAddress(res.address))
                this.setData({
                    address:res.address
                })
                console.log("address: ",this.data.address)
            }
        })
        
      },
      fail: (err) => {
        console.error('获取位置失败:', err);
      },
      complete: () => {
        console.log('位置获取操作已完成');
      }
    });
  },

  

//   onClickIcon() {
//     Toast('点击图标');
//   },

getQRCode: function () {
    var that=this
    // 请求后端接口获取二维码图片
    wx.request({
      url: 'http://localhost:8080/wechat/generateQRCode/' + that.data.campId, // 替换为你的后端接口URL
      method: 'GET',
      responseType: 'arraybuffer', // 指定返回类型为arraybuffer，用于处理图片数据
      success: (res) => {
        if (res.statusCode === 200) {
          // 将图片数据转换为Base64编码
          const base64 = wx.arrayBufferToBase64(res.data);
          // 设置图片URL为Base64编码的字符串（注意：小程序中直接使用Base64图片有大小限制）
          // 或者，你可以将图片数据上传到云存储，并获取图片的URL
          // 这里为了简化示例，直接使用Base64
          that.setData({
            qrCodeImage: 'data:image/png;base64,' + base64
          });
          console.log("qrCodeImage: ",this.data.qrCodeImage)
          return this.data.qrCodeImage;
        } else {
          // 处理请求失败的情况
          console.error('Failed to get QR code:', res.statusCode, res.data);
        }
      },
      fail: (err) => {
        // 处理请求失败的情况
        console.error('Request failed:', err);
      }
    });
},

  //结算按钮
  onClickButton() {
       //从本地获取购物车缓存
    var carList=wx.getStorageSync('cartList-' + this.data.campId)
    console.log("结算购物车缓存： ",carList)
  
    console.log("this: ",this.data)
    
    var that=this
   
    // this.getQRCode()
    that.setData({
        obj:{
            userId:wx.getStorageSync('userInfo').userId,
            campId:that.data.campId,
            total:that.data.amount,
            // qrcode:'data:image/png;base64,' + base64, //二维码
            qrcode:"",
            orderDetails:[...carList]
        }
    })
 


    http.goodsOrderAdd(that.data.obj).then((res)=>{
        console.log("goodsOrderAdd: ",res)
        var orderId=res.msg
        if(res.code==200){
            //订单信息添加成功
            //清空当前购物车
            wx.setStorageSync('cartList-' + that.data.campId,[])
            that.setData({
                cartList: []
            })
            //刷新购物车
            that.setCartList()

            // console.log(this.data.appointmentList)
            //刷新当前商品的数量
            for(var i=0;i<that.data.goodsList.length;i++){
                that.data.goodsList[i].num=0
            }

            // console.log( that.data.goodsList)
            that.data.appointmentList.goodsList=that.data.goodsList
            that.setData({
                goodsList: that.data.goodsList,
                appointmentList:that.data.appointmentList
              })
             // 请求后端接口获取二维码图片
    wx.request({
        url: 'http://localhost:8080/wechat/generateQRCode/' + orderId, // 替换为你的后端接口URL
        method: 'GET',
        responseType: 'arraybuffer', // 指定返回类型为arraybuffer，用于处理图片数据
        success: (res) => {
          if (res.statusCode === 200) {
            // 将图片数据转换为Base64编码
            const base64 = wx.arrayBufferToBase64(res.data);
            // 设置图片URL为Base64编码的字符串（注意：小程序中直接使用Base64图片有大小限制）
            // 或者，你可以将图片数据上传到云存储，并获取图片的URL
            // 这里为了简化示例，直接使用Base64
            var object=this.data.obj
            object.qrcode= 'data:image/png;base64,' + base64
            object.orderId=orderId
            that.setData({
              obj:object
            });  
            console.log("qrCodeImage: ",this.data)
            //修改订单信息，将二维码信息加入
            http.goodsOrderUpdata(object).then((res)=>{
                console.log("修改订单信息，将二维码信息加入",res)
            })
          } else {
            // 处理请求失败的情况
            console.error('Failed to get QR code:', res.statusCode, res.data);
          }
        },
        fail: (err) => {
          // 处理请求失败的情况
          console.error('Request failed:', err);
        }
        
      });   

    }
        
    })


  



    // var that=this
    // Toast('点击按钮');
   
    this.setData({
        flag:true
    })
   
    
    // var object=this.data.obj
    // console.log("object: ",object)
   
  },

  // 弹出购物车页面
  onShowCart() {
    this.setData({
      showCart: true
    })
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  onPopupClose() {
    this.setData({ showCart: false });
  },
  onQrCodeClose() {
    this.setData({ flag: false });
  },
})